//
//  RootViewController.m
//  CMNavBar
//
//  Created by Chaiyasit Tayabovorn on 2/23/11.
//  Copyright 2011 CodeMobiles Co.,Ltd. All rights reserved.
//

#import "RootViewController.h"
#import "Constants.h"


@implementation RootViewController
@synthesize nameTextField;
@synthesize cmTableView, menuList, imagesList, infoViewController;
@synthesize langSegmentedControl;
@synthesize appPlist;

#define thaiShowSegmentIndex 0

static NSArray *pageNames = nil;


- (IBAction)tryMePressed:(id)sender {
	int segment = [langSegmentedControl selectedSegmentIndex];
	
	if(segment == thaiShowSegmentIndex) {
        // NSString *nameString = [NSString stringWithFormat:@"เลือกกรุ๊ปเลือดของคุณ %@", nameTextField.text];
        nameTextField.text = @"555555555555555555555555555";
        NSLog(@"1111");
        //UIAlertView *tryMeAlertview = [[UIAlertView alloc] initWithTitle: @"HelloWorld" 
                                                               //  message: nameString
          //                                                      delegate: self 
                                                       //cancelButtonTitle: @"ปิด" 
            //                                           otherButtonTitles: nil];
        
        
        
        
		//[tryMeAlertview show];
		//[tryMeAlertview release];
	} else {
		//NSString *nameString = [NSString stringWithFormat:@"Choose Blood Type %@", nameTextField.text];
		UIAlertView *tryMeAlertview = [[UIAlertView alloc] initWithTitle: @"HelloWorld" 
                                                             //    message: nameString
                                                                delegate: self 
                                                       //cancelButtonTitle: @"Close" 
                                                       otherButtonTitles: nil];
		[tryMeAlertview show];
		[tryMeAlertview release];
	}
}


- (IBAction)onBackgroundClick:(id)sender {
    [nameTextField resignFirstResponder];
}
#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
	[super viewDidLoad];
    NSString *path = [[NSBundle mainBundle] bundlePath];
    
    // path = .../../...
    
	NSString *plistPath = [path stringByAppendingPathComponent:@"Languages.plist"];
    // path = .../../.../Languages.plist
    
	self.appPlist = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
	
	NSString *nameString;
	//NSString *clickString;
    
    nameString = [self.appPlist valueForKey:@"ThaiName"];//ค่าของ key
    //clickString = [self.appPlist valueForKey:@"ThaiClick"];
    
    NSLog(@"Value Of ThaiName: %@", nameString);// print
    //NSLog(@"Value Of ThaiClick: %@", clickString);
    
    
	//nameLabel.text = nameString;//เอาค่ายัดไปในปุ่ม 
	//[clickButton setTitle:clickString forState:UIControlStateNormal];
    [nameTextField becomeFirstResponder]; // outlet ที่ต้องพิมข้อความเข้าไป
	
	// Make the title of this page the same as the title of this app
	self.title = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
	
    // form mutable array changable rather
	self.menuList = [NSMutableArray array];
    self.imagesList = [NSMutableArray array];
	
	if (!pageNames)
	{
		pageNames = [[NSArray alloc] initWithObjects:@"PageOne",@"PageTwo",@"PageThree",@"PageFour", @"PageFive", nil];//will show page that you want
	}
	
    int i = 1;
	for(NSString *pageName in pageNames)
	{
        // To add dictionary obj into array obj.
        // + (id)dictionaryWithObjectsAndKeys:(id)firstObject, ... NS_REQUIRES_NIL_TERMINATION;
		[self.menuList addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                  NSLocalizedString([pageName stringByAppendingString:@"Title"], @""), kTitleKey,
                                  //NSLocalizedString([pageName stringByAppendingString:@"Explain"], @""), kDetailKey,
                                  nil]];
		
        //[self.imagesList addObject:[NSString stringWithFormat:@"%d.png", i]];
        i++;
	}
    
   
	
    // form bar items
	UIButton* infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
	[infoButton addTarget:self action:@selector(modalViewAction:) forControlEvents:UIControlEventTouchUpInside];
	UIBarButtonItem* infoButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton];
	self.navigationItem.rightBarButtonItem = infoButtonItem;
    
    UIBarButtonItem *button = [[UIBarButtonItem alloc]initWithTitle:@"Style" style:UIBarButtonItemStylePlain target:self action:@selector(styleAction:)];
    self.navigationItem.leftBarButtonItem = button;
	[infoButton release];
    [infoButtonItem release];

}
- (IBAction)toggleChangeLang:(id)sender {
    
    int segment = [sender selectedSegmentIndex];
    
    //NSString *nameString;
    //NSString *clickString;
    if(segment == thaiShowSegmentIndex) {
        nameTextField.text = [self.appPlist valueForKey:@"ThaiName"];
        nameTextField.textAlignment = UITextAlignmentCenter;        
        //clickString = [self.appPlist valueForKey:@"ThaiClick"];
    } else {
        nameTextField.text = [self.appPlist valueForKey:@"EngName"];
        nameTextField.textAlignment = UITextAlignmentCenter;
       // clickString = [self.appPlist valueForKey:@"EngClick"];
    }
    //nameLabel.text = nameString;
    
   // [clickButton setTitle:clickString forState:UIControlStateNormal];
    
}

#pragma mark -
#pragma mark Table view data source

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return menuList.count;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	static NSString *CellIdentifier = @"Cell";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
        
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.textAlignment = UITextAlignmentRight;
		cell.textLabel.backgroundColor = [UIColor clearColor];
		cell.textLabel.opaque = NO;
		cell.textLabel.textColor = [UIColor blackColor];
		cell.textLabel.highlightedTextColor = [UIColor whiteColor];
		cell.textLabel.font = [UIFont boldSystemFontOfSize:18];
		
					
	}
	
	// Configure the cell.
	NSDictionary *dataDictionary = [menuList objectAtIndex:indexPath.row];
	NSLog(@"textLabel: %@", [dataDictionary valueForKey:kTitleKey]);
	//NSLog(@"detailLabel: %@", [dataDictionary valueForKey:kDetailKey]);
	
    //NSString *imageName = [imagesList objectAtIndex:indexPath.row];//show image 
    //cell.imageView.image = [UIImage imageNamed:imageName];
	cell.textLabel.text = [dataDictionary valueForKey:kTitleKey];
	cell.detailTextLabel.text = [dataDictionary valueForKey:kDetailKey];
	
	return cell;
}


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	NSMutableDictionary *rowData = [self.menuList objectAtIndex:indexPath.row];
	UIViewController *targetViewController = [rowData objectForKey:kViewControllerKey];
	if (!targetViewController)
	{
		// The view controller has not been created yet, create it and set it to our menuList array
		NSString *viewControllerName = [[pageNames objectAtIndex:indexPath.row] stringByAppendingString:@"ViewController"];
		targetViewController = [[NSClassFromString(viewControllerName) alloc] initWithNibName:viewControllerName bundle:nil];
		[rowData setValue:targetViewController forKey:kViewControllerKey];
		[targetViewController release];
	}
	[self.navigationController pushViewController:targetViewController animated:YES];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
	[super didReceiveMemoryWarning];
	
	// Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [self setNameTextField:nil];
    [langSegmentedControl release];
    langSegmentedControl = nil;
	// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
	// For example: self.myOutlet = nil;
}


- (void)dealloc {
    [langSegmentedControl release];
    [nameTextField release];
	[super dealloc];
}


- (IBAction)tabNavigator:(id)sender {
    profilesViewController *profileView = [[[profilesViewController alloc]initWithNibName:@"profilesViewController" bundle:nil]autorelease];
    
    [self.navigationController pushViewController:profileView animated:YES];
}

- (IBAction)tabButton:(id)sender {
//    profilesViewController *profileView = [[[profilesViewController alloc]initWithNibName:@"profilesViewController" bundle:nil]autorelease];
//    
//    [self.navigationController pushViewController:profileView animated:YES];
    

}
- (IBAction) styleAction: (id)sender{
	//UIActionSheet *styleAlert = [[UIActionSheet alloc] initWithTitle:@"Choose a UIBarStyle" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Default", @"BlackOpaque",@"BlackTranslucent", nil, nil];
	UIActionSheet *styleAlert = [[UIActionSheet alloc]initWithTitle:@"Choose a UIBarStyle" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Default", @"BlackOpaque",@"BlackTranslucent", nil];
    
	//styleAlert.actionSheetStyle = self.navigationController.navigationBar.barStyle;
	[styleAlert showInView:self.view];
	[styleAlert release];
}

#pragma mark -
#pragma mark UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)modalView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	// Change the navigation bar style, also make the status bar match with it

	switch (buttonIndex)
	{
		case 0:
		{
			[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
			self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
			break;
		}
		case 1:
		{
			[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackOpaque;
			self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
			break;
		}
		case 2:
		{
			[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackTranslucent;
			self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
			break;
		}
	}
}


#pragma mark -
#pragma mark API

-(IBAction) modalViewAction:(id)sender
{
	if (self.infoViewController == nil)
		self.infoViewController = [[[InfoViewController alloc] initWithNibName:
                                    NSStringFromClass ([InfoViewController class]) 
                                                                        bundle:nil] autorelease];
	
	[self.navigationController presentModalViewController:self.infoViewController animated:YES];																							 
}


- (void)keyboardWillShow:(NSNotification *)notif
{
    //keyboard will be shown now. depending for which textfield is active, move up or move down the view appropriately
    
    if ([nameTextField isFirstResponder] && self.view.frame.origin.y >= 0)
    {
        [self setViewMovedUp:YES];
    }
    else if (![nameTextField isFirstResponder] && self.view.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }
}


- (void)viewWillAppear:(BOOL)animated
{
    
    
    // register for shown keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) //--method name keybord will show
                                                 name:UIKeyboardWillShowNotification object:self.view.window]; 
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardDidHideNotification object:self.view.window]; 
    
}

@end

